<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

//包含公用的方法 前台和后台公用
include __ROOT__ . "../include/function/common_function.php";

/**
 * 后台常见的方法
 * author Cuil <lntschampion@163.com>
 */
//获取指定长度的随机字符串
function getRandChar($length) {

    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;

    for ($i = 0; $i < $length; $i++) {
        //rand($min,$max)生成介于min和max两个数之间的一个随机整数
        $str .= $strPol[rand(0, $max)];
    }

    return $str;
}



/**截取字符串
 * $str 字符串
 * $len 长度 
 * $dot true | false 是否显示... 
 */ 
function substring($str,$start=0,$len,$code='utf8',$dot=true){
     
    $str = strip_tags(htmlspecialchars_decode($str));
   
    $str=trim($str,' ');
    
    
    $str=trim($str,'　');
    $str=trim($str,' ');
    
    $str=str_replace('&nbsp;','',$str);
    $str=str_replace(' &nbsp;','',$str);
    $str=str_replace('　','',$str);
    $str=str_replace(' ','',$str);
    

    $str_len = mb_strlen($str,$code);
    $sub_str = $str;
    if($str_len>$len){
        $sub_str = mb_substr($str,$start,$len,$code);
        if($dot){
            $sub_str = $sub_str.'...';
        }
    }else{
        $sub_str = $sub_str;
    }
    return $sub_str;
}

//获取当前时间是周几
function getWeekName($data, $format = '周') {

    $week = date("D ", $data);

    switch ($week) {

        case "Mon ":
            $current = $format . "一";
            break;
        case "Tue ":
            $current = $format . "二";
            break;
        case "Wed ":
            $current = $format . "三";
            break;
        case "Thu ":
            $current = $format . "四";
            break;
        case "Fri ":
            $current = $format . "五";
            break;
        case "Sat ":
            $current = $format . "六";
            break;
        case "Sun ":
            $current = $format . "日";
            break;
    }

    return $current;
}

/**
 * [正则验证手机号码]
 * @author fans
 * @date 2015-7-10
 * */
if (!function_exists("is_mobile_phone")) {

    function is_mobile_phone($mobile) {
        $pattern = "/^(13|15|18|17){1}\d{9}$/";
        return preg_match($pattern, $mobile);
    }

}


/* * ·
 * [手机号中间用星号代替]  
 * @author limeng
 * @date 2015-8-05
 * */
if (!function_exists('format_mobile_phone')) {

    function format_mobile_phone($mobile_phone) {
        return substr($mobile_phone, 0, 3) . "****" . substr($mobile_phone, 7, 4);
    }

}


/**
 * [正则验证邮箱]
 * @author fans
 * @date 2016-2-29
 * */
if (!function_exists("is_email")) {

    function is_email($email) {
        return strlen($email) > 8 && preg_match("/^[-_+.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+([a-z]{2,4})|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email);
    }

}

/**
 * 缓存目录
 */
if (!function_exists('get_cache_key')) {

    function get_cache_key($id, $key) {

        $dir = dir_rule($id);
        $path = $dir;

        $date = date('Ymd', time());

        $dir = APPPATH . 'cache/' . $date . '/' . $path;
        if (!file_exists($dir)) {
            @mkdir($dir, 0777, true);
        }
        return $date . '/' . $path . $key;
    }

}

//获取积分的对称加密算法
class DES_ADMIN {

    static $key = '$&$(@*';

    static function encrypt($encrypt) {
        $key = self::$key;
        // 根据 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 加入 Padding
        $block = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_ECB);
        $pad = $block - (strlen($encrypt) % $block);
        $encrypt .= str_repeat(chr($pad), $pad);
        // 不需要设定 IV 进行加密
        $passcrypt = mcrypt_encrypt(MCRYPT_DES, $key, $encrypt, MCRYPT_MODE_ECB);
        return base64_encode($passcrypt);
    }

    static function decrypt($decrypt) {
        $key = self::$key;
        // 不需要设定 IV
        $str = mcrypt_decrypt(MCRYPT_DES, $key, base64_decode($decrypt), MCRYPT_MODE_ECB);

        // 根据 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 移除 Padding
        $pad = ord($str[strlen($str) - 1]);
        return substr($str, 0, strlen($str) - $pad);
    }

}

/**
 * @记录系统操作日志文件到数据库里面 
 * *sql 是要插入数据库中的 log_sql的值 
 * $action 动作
 * $person 操作人
 * $ip ip地址
 * status 操作是否成功 1成功 0失败
 * message 失败信息
 * groupname_ 定义数据库连接信息的时候的 groupname
 */
if (!function_exists("write_action_log")) {

    function write_action_log($sql, $url = '', $person = '', $ip = '', $status = '1', $message = '', $groupname_ = "default") {
        if (!config_item('is_write_log_to_database')) {//是否记录日志文件到数据表中
            return false;
        }

        $sql = str_replace("\\", "", $sql); // 把\进行过滤掉
        $sql = str_replace("%", "\%", $sql); // 把 '%'前面加上\
        $sql = str_replace("'", "\'", $sql); // 把 ''过滤掉
        $message = daddslashes($message);
        $time = date("Y-m-d H:i:s", time());
        $time_table = date("Ym", time());

        $table_pre = table_pre($groupname_);

        $sql_table = <<<EOT
CREATE TABLE IF NOT EXISTS `{$table_pre}common_log_{$time_table}` (
  `log_id` mediumint(8) NOT NULL auto_increment,
  `log_url` varchar(50) NOT NULL,
  `log_person` varchar(16) NOT NULL,
  `log_time` datetime NOT NULL,
  `log_ip` char(15) NOT NULL,
  `log_sql` text NOT NULL,
  `log_status` tinyint(1) NOT NULL default '1',
  `log_message` varchar(255) NOT NULL,
  PRIMARY KEY  (`log_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;		
EOT;
        $ci = &get_instance(); //初始化 为了用方法
        $d = $ci->load->database($groupname_, true);
        $d->query($sql_table);
        $sql_log = "INSERT INTO `{$table_pre}common_log_{$time_table}`(`log_url`,`log_person`,`log_time`,`log_ip`,`log_sql`,`log_status`,`log_message`)VALUES('{$url}','{$person}','{$time}','{$ip}','{$sql}','{$status}','{$message}')";
        $d->query($sql_log);
    }

}

/**
 * 将数据格式化成树形结构
 * @author CCC
 * @param array $items
 * @return array
 */
if (!function_exists("genTree9")) {

    function genTree9($items, $id = 'id', $pid = 'pid', $child = 'children') {
        $tree = array(); //格式化好的树
        foreach ($items as $item)
            if (isset($items[$item[$pid]]))
                $items[$item[$pid]][$child][] = &$items[$item[$id]];
            else
                $tree[] = &$items[$item[$id]];
        return $tree;
    }

}

/**
 * 格式化select
 * @author CCC
 * @param array $parent
 * @deep int 层级关系 
 * @return array
 */
function getChildren($parent, $deep = 0) {
    foreach ($parent as $row) {
        $data[] = array("id" => $row['id'], "name" => $row['name'], "pid" => $row['parentid'], 'deep' => $deep, 'url' => $row['url']);
        if (isset($row['childs']) && !empty($row['childs'])) {
            $data = array_merge($data, getChildren($row['childs'], $deep + 1));
        }
    }
    return $data;
}

/**
 * 格式化select,生成options
 * @author CCC
 * @param array $parent
 * @deep int 层级关系 
 * @return array
 */
function getChildren2($parent, $deep = 0, $id = 'id', $pid = 'pid', $name = 'typename', $children = 'children') {
    foreach ($parent as $row) {
        $data[] = array("id" => $row[$id], "name" => $row[$name], "pid" => $row[$pid], 'deep' => $deep);
        if (isset($row[$children]) && !empty($row[$children])) {
            $data = array_merge($data, getChildren2($row[$children], $deep + 1, $id, $pid, $name, $children));
        }
    }
    return $data;
}

/**
 * 格式化数组，用于分类缩进
 * @author CCC
 * @param array $list
 * @return array
 */
function tree_format(&$list, $pid = 0, $level = 0, $html = '--', $pid_string = 'pid', $id_string = 'id') {
    static $tree = array();
    foreach ($list as $v) {
        if ($v[$pid_string] == $pid) {
            $v['sort'] = $level;
            $v['html'] = str_repeat($html, $level);
            $tree[] = $v;
            tree_format($list, $v[$id_string], $level + 1, $html);
        }
    }
    return $tree;
}

/**
 * 显示页面
 * @author CCC
 * @param string $message 错误信息
 * @param string $url 页面跳转地址
 * @param string $iserror 是否错误 1正确 0错误
 * @param string $timeout 时间
 * @param string $params 其他参数前面加? 例如?id=122&time=333
 */
if (!function_exists('showmessage')) {

    function showMsg($message = '', $url = '', $iserror = 1, $params = '', $top = '', $ky = "", $timeout = '3') {

        $imageUrl = config_item("image_url");
        if ($iserror == 1) {//正确
            include APPPATH . '/errors/success.php';
        } else {
            include APPPATH . '/errors/fail.php';
        }
        exit();
    }

}

/**
 * 获取后台登陆的数据，其中参数主要是为了 ，有时候用插件上传图片的时候 登陆状态消失
 * @author CCC
 * @param $string 解密的值
 * @return array
 */
if (!function_exists("decode_data")) {

    function decode_data($string = '') {
        $data = array();
        $encode_string = '';
        $encode_string = ($string != "" ) ? $string : (isset($_COOKIE['admin_auth']) ? $_COOKIE['admin_auth'] : '');
        if (empty($encode_string)) {
            return $data;
        }

        $encode_string = auth_code($encode_string, "DECODE", config_item("s_key"));
        $data = unserialize($encode_string);
        return $data;
    }

}

/**
 * 获取ids数据
 * @author CCC
 * @param $array array(1,3,4,5,6,7)
 * @return String 1,3,4,5,6,7
 */
if (!function_exists("get_ids")) {

    function get_ids($ids = '') {
        if ($ids) {
            $id = '';
            for ($i = 0; $i < count($ids); $i++) {
                if (intval($ids[$i]) <= 0) {
                    continue;
                }
                $id.=intval($ids[$i]) . ",";
            }
            $id = rtrim($id, ",");
            return $id;
        } else {
            return '';
        }
    }

}

//获取 某个月的最大天数（最后一天）
function getMonthLastDay($month, $year) {
    switch ($month) {
        case 4 :
        case 6 :
        case 9 :
        case 11 :
            $days = 30;
            break;
        case 2 :
            if ($year % 4 == 0) {
                if ($year % 100 == 0) {
                    $days = $year % 400 == 0 ? 29 : 28;
                } else {
                    $days = 29;
                }
            } else {
                $days = 28;
            }
            break;
        default :
            $days = 31;
            break;
    }
    return $days;
}

/**
 * url签名加密解密类
 */
class url_check {

    /**
     * checksum加密验证
     */
    function encode($str) {
        $len = strlen($str);
        $v = '';
        for ($i = 0; $i < $len; $i++) {
            $h = ((ord(substr($str, $i, 1)) ^ 0x7f) & 0xf) + ord('a');
            $l = (((ord(substr($str, $i, 1)) ^ 0x7f) >> 4) & 0xf) + ord('a');
            $v.=chr($l) . chr($h);
        }
        return $v;
    }

    /**
     * checksum解密验证
     */
    function decode($str) {
        $len = strlen($str);
        $v = '';
        for ($i = 0; $i < $len; $i = $i + 2) {
            $h = (ord(substr($str, $i, 1)) - ord('a'));
            $l = (ord(substr($str, $i + 1, 1)) - ord('a'));
            $v.=chr(($h << 4 | $l) ^ 0x7f);
        }
        return $v;
    }

}



/**
 * 排序
 * @param  [type] $arrays     [description]
 * @param  [type] $sort_key   [description]
 * @param  [type] $sort_order [description]
 * @param  [type] $sort_type  [description]
 * @return [type]             [description]
 */
function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){   
	if(is_array($arrays)){   
		foreach ($arrays as $array){   
			if(is_array($array)){   
				$key_arrays[] = $array[$sort_key];   
			}else{   
				return false;   
			}   
		}   
	}else{   
		return false;   
	}  
	array_multisort($key_arrays,$sort_order,$sort_type,$arrays);   
	return $arrays;   
} 

?>
